<template>
  <div v-if="mode">
    <div class="flex justify-between align-center gap-2">
      <div>
        <a-input-number :min="0" @change="confirm" v-model:value="active">
          <template #addonBefore>序号</template>
        </a-input-number>
      </div>
      <div class="system__icon" @click="mode = !mode">
        <MoreOutlined />
      </div>
    </div>
  </div>
  <a-card title="排序" class="w-[100%] sort-card" v-else="mode">
    <template #extra>
      <div class="system__icon" @click="mode = !mode">
        <MinusOutlined />
      </div>
    </template>
    <div class="flex flex-wrap g-8">
      <div
        class="item system__hover flex flex-s"
        v-for="item in comList"
        :key="item"
        :class="{ active: active === item }"
        @click="selectItem(item)"
      >
        <span v-if="active === item">{{ item }}</span>
      </div>
    </div>
  </a-card>
</template>

<script setup lang="ts">
import { MoreOutlined } from '@ant-design/icons-vue';

const active = ref<number>(1);
const maxLength = ref<number[]>([]);
const emit = defineEmits(['update:modelValue']);

const mode = ref(true);
const props = defineProps<{
  /* 当前的排序 */
  modelValue: number;
  /* 最大的排序值 */
  total?: number;
}>();
const confirm = () => {
  emit('update:modelValue', active.value);
};
const selectItem = (num: number) => {
  active.value = num;
  confirm();
};

watch(
  props,
  () => {
    active.value = Number(props.modelValue);
    if (typeof props.total === 'number') {
      let total = props.total <= 0 ? 20 : props.total;
      maxLength.value = Array.from({ length: total + 1 }, (_, i) => i);
    }
  },
  {
    deep: true,
    immediate: true,
  },
);

const comList = computed(() => {
  return maxLength.value.sort((a, b) => {
    return a - b;
  });
});
</script>

<style lang="scss" scoped>
$wh: 32px;
.item {
  flex-basis: $wh;
  height: $wh;
  border: 1px solid #ddd;
  border-radius: var(--radius);
  cursor: pointer;
  opacity: 0.8;
}
.active {
  background: var(--primary) !important;
  opacity: 1;
  color: white;
}
.system__icon {
  width: 24px;
  height: 24px;
}
.sort-card {
  :deep(.ant-card-body) {
    max-height: 400px;
    overflow-y: auto;
  }
}
</style>
